package cn.example.demo.service.impl;

import cn.example.demo.pojo.Article;
import cn.example.demo.service.ArticleService;
import cn.example.demo.vo.ArticleVo;
import cn.example.demo.vo.Paging;
import com.jfinal.plugin.activerecord.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @ProjectName: springbootmybatisinvoicings
 * @Package: cn.example.demo.service.impl
 * @ClassName: ArticleServiceImpl
 * @Author: liang
 * @Description:
 * @Date: 2020/4/25 10:31
 * @Version: 1.0
 */
@Service
@Slf4j
public class ArticleServiceImpl implements ArticleService {
    private static final Article dao = new Article().dao();

    @Override
    public Object pageinate(int pageNumber, int pageSize) {
        Paging paging = new Paging();//asc
        Page<Record> paginate1 = Db.paginate(pageNumber, pageSize, "select *", "from article order by id desc");
        BeanUtils.copyProperties(paginate1, paging);
        paging.setList(maps(paginate1.getList()));
        return paging;
    }

    @Override
    public Object pageinate(int pageNumber, int pageSize, String test, String save) {
        //StringBuffer sb= new StringBuffer();
        Page<Record> paginate=null;
        if (!test.trim().equals("")) {
            SqlPara findArticle2 = Db.getSqlPara("findArticle2", test);
            paginate = Db.paginate(pageNumber, pageSize,findArticle2);
        }
        Paging paging = new Paging();//asc
        // Page<Record> paginate1 = Db.paginate(pageNumber, pageSize, "select *", "from article order by id desc");
        BeanUtils.copyProperties(paginate, paging);
        paging.setList(maps(paginate.getList()));
        return paging;
    }

    @Override
    public Object select() {
        List<Record> records = Db.find("select * from article ");
        System.out.println(records.get(0).getColumns());
        return maps(records);
    }

    private List<Map<String, Object>> maps(List<Record> list) {
        List<Map<String, Object>> maps = new ArrayList<>();
        for (Record article : list) {
            Map<String, Object> columns = article.getColumns();
            maps.add(columns);
        }
        return maps;
    }

    @Override
    public boolean delete(int id) {
        return dao.deleteById(id);
    }

    @Override
    public Article findById(int id) {
        Article byId = dao.findById(id);
        return byId;
    }

    @Override
    public boolean update(int id, String save, String test) {
        return dao.findById(id).set("test", test).set("save", save).update();
    }

    @Override
    public boolean insert(ArticleVo articleVo) {
        return new Article().set("test", articleVo.getTest()).set("save", articleVo.getSave()).save();
    }
}
